<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/1 0001
 * Time: 15:47
 */

namespace App\HttpController;

use App\Model\MypicModel;
use EasySwoole\Http\AbstractInterface\Controller;
use App\Libs;
use Illuminate\Support\Facades\App;

class Upload extends Base
{
    public function index()
    {
        if($this->request()->getMethod() == 'POST'){
            $img_file = $this->request()->getUploadedFile('file');
            if (!$img_file) {
                return $this->writeJson(500, '请选择上传的文件');
            }

            if ($img_file->getSize() > 1024 * 1024 * 5) {
                return $this->writeJson(500, '图片不能大于5M！');
            }

            $MediaType = explode("/", $img_file->getClientMediaType());
            $MediaType = $MediaType[1] ?? "";
            if (!in_array($MediaType, ['png', 'jpg', 'gif', 'jpeg', 'pem', 'ico'])) {
                return $this->writeJson(500, '文件类型不正确！');
            }

            $path =  '/Static/file/image/upload/';
            $dir =  EASYSWOOLE_ROOT.$path;
            $uid = uniqid(date('YmdHis'));

            $picname = explode('.',$img_file->getClientFileName());
            $fileName = $uid.'.'.$picname[1];

            if(!is_dir($dir)) {
                mkdir($dir, 0777 , true);
            }

            $flag = $img_file->moveTo($dir.$fileName);

            $md5 = sha1_file($dir.$fileName);
            $res = MypicModel::create()->get(['filehash'=>$md5]);
            if($res != null){
                unlink($dir.$fileName);
                return $this->writeJson(500,'上传失败,文件已存在');
            }

            $libs = new Libs\PicLib();

            $thumbName = $uid.'_thumb.'.$picname[1];
            if($img_file->getSize()/1024 > 150){
                $ratio = 0.3;
            }else{
                $ratio = 0.5;
            }
            $libs->reSizeImg($dir.$fileName,$dir.$thumbName,null,null,$ratio);

            $data = [
                'ip' => $this->request()->getHeader('x-real-ip')[0],
                'userid' => 100,
                'filename' => $fileName,
                'fileurl' => $path.$fileName,
                'filehash' => $md5,
                'filethumb' => $path.$thumbName,
                'size' => sprintf('%.1f',$img_file->getSize()/1024),
                'source' => 1,
                'created_at' => date('Y-m-d H:i:s'),
            ];

            $file = new MypicModel($data);
            $res = $file->save();
            $data['fildata_id'] = json_encode($res,256);

            if($flag) {
                $this->writeJson(0,'上传成功',$data);
            } else {
                $this->writeJson(500,'上传失败');
            }
        }else{
            $this->render('upload');
        }
    }
}